package com.ldj.tim.server.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ldj.tim.common.constant.MqConstants;
import com.ldj.tim.common.pojo.P2PInfo;
import com.ldj.tim.server.mapper.TestProduct;
import com.ldj.tim.server.mapper.TestProductMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author majinhui
 * @description
 * @create 2024/11/12 10:12
 **/
@RestController
@RequestMapping("mq")
public class MessageTestController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
     @Autowired
    private TestProductMapper testProductMapper;

    @GetMapping("test")
    public void sendMsg(@RequestParam("type") Integer type) {
        /**
         * 1、到交换器失败
         * 2、到队列失败
         * 3、basicNack
         */
        P2PInfo p2PInfo = new P2PInfo();
        if (type == 1) {
            p2PInfo.setMessage("投递到交换器失败");
            p2PInfo.setMsgId("1");
            rabbitTemplate.convertAndSend("123", "", p2PInfo);
        } else if (type == 2) {
            p2PInfo.setMessage("投递到队列失败");
            p2PInfo.setMsgId("2");
            rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_NAME, "", p2PInfo);
        } else if (type == 3) {
            p2PInfo.setMessage("消息被拒绝");
            p2PInfo.setMsgId("3");
            rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_NAME, MqConstants.ROUTING_KEY, p2PInfo);
        }

    }

    @GetMapping("/order")
    public boolean updateMessage(){
// 构建 UpdateWrapper 条件
        UpdateWrapper<TestProduct> updateWrapper = new UpdateWrapper<>();
        Integer productId = 1;
        updateWrapper
            .eq("product_id", productId) // 指定 product_id
            .gt("stock", 0)             // 确保库存大于 0
            .setSql("stock = stock - 1") // 减库存
            .setSql("version = version + 1"); // 更新版本号

        // 执行更新，返回受影响的行数
        int rows = testProductMapper.update(null, updateWrapper);

        // 如果受影响行数大于 0，表示扣减成功
        return rows > 0;
    }
}
